package com.liyao.windowtest4.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @program: torque
 * @description:
 * @author: liu yan
 * @create: 2024-10-15 16:39
 */
public class SocketClientUtil implements AutoCloseable{
    private String hostname;
    private int port;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public SocketClientUtil(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
    }

    public void connect() throws UnknownHostException, IOException {
        System.out.println("连接扳手Socket。。。");
        socket = new Socket(hostname, port);
        socket.setSoTimeout(3000);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void sendMessage(String message) {
//        System.out.println("向扳手发送信息："+message);
        out.print(message);
        out.flush();
    }

    public String receiveMessage() throws IOException {
        return in.readLine();
    }

    public void close() throws IOException {
        if (in != null) in.close();
        if (out != null) out.close();
        if (socket != null) socket.close();
    }

}
